package com.ruoyi.web.controller.system;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Scanner;

@RequestMapping("/onlyOffice")
@RestController
public class OnlyOffice {
    @RequestMapping("/index")
    public ModelAndView index(){
        return new ModelAndView("onlyOffice");
    }

    @RequestMapping("/download")
    public String downExcel(HttpServletResponse response) throws UnsupportedEncodingException {
        File file = new File("F:\\Desktop\\111.docx");
        // 如果文件存在，则进行下载
        if (file.exists()) {
            // 配置文件下载
            response.setHeader("content-type", "application/octet-stream");
            response.setContentType("application/octet-stream");
            // 下载文件能正常显示中文
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode("aaa.doc", "UTF-8"));
            // 实现文件下载
            byte[] buffer = new byte[1024];
            FileInputStream fis = null;
            BufferedInputStream bis = null;
            try {
                fis = new FileInputStream(file);
                bis = new BufferedInputStream(fis);
                OutputStream os = response.getOutputStream();
                int i = bis.read(buffer);
                while (i != -1) {
                    os.write(buffer, 0, i);
                    i = bis.read(buffer);
                }
                System.out.println("Download  successfully!");
                return "successfully";

            } catch (Exception e) {
                System.out.println("Download  failed!");
                return "failed";

            } finally {
                if (bis != null) {
                    try {
                        bis.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if (fis != null) {
                    try {
                        fis.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
        return "";
    }
    /**
     * 保存修改后的
     * @param request
     * @param response
     */
    @PostMapping("/docx/save")
    public void saveWord(HttpServletRequest request, HttpServletResponse response) {
        try {
            PrintWriter writer = response.getWriter();
            String body = "";
            try {
                Scanner scanner = new Scanner(request.getInputStream());
                scanner.useDelimiter("\\A");
                body = scanner.hasNext() ? scanner.next() : "";
                scanner.close();
            } catch (Exception ex) {
                writer.write("get request.getInputStream error:" + ex.getMessage());
                return;
            }
            if (body.isEmpty()) {
                writer.write("empty request.getInputStream");
                return;
            }
            JSONObject jsonObj = JSON.parseObject(body);
            int status = (Integer) jsonObj.get("status");
            int saved = 0;
            if (status == 2 || status == 3)//MustSave, Corrupted
            {
                String downloadUri = (String) jsonObj.get("url");
                try {
                    URL url = new URL(downloadUri);
                    java.net.HttpURLConnection connection = (java.net.HttpURLConnection) url.openConnection();
                    InputStream stream = connection.getInputStream();
                    if (stream == null) {
                        throw new Exception("Stream is null");
                    }
                    // 从请求中获取要覆盖的文件参数定义"path"
//                    String path = request.getParameter("path");
                    String path = "F:\\Desktop\\111.docx";
                    System.err.println("====路径:"+path);
                    File savedFile = new File(path);
                    try (FileOutputStream out = new FileOutputStream(savedFile)) {
                        int read;
                        final byte[] bytes = new byte[1024];
                        while ((read = stream.read(bytes)) != -1) {
                            out.write(bytes, 0, read);
                        }
                        out.flush();
                    }
                    connection.disconnect();
                } catch (Exception ex) {
                    saved = 1;
                    ex.printStackTrace();
                }
            }
            System.out.print("编辑完成--------------11111");
            writer.write("{\"error\":" + saved + "}");
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

}
